/**
 *
 * @param fn  {Function}需要防抖的函数
 * @param delay {number} 防抖延迟时间(毫秒)
 * @param immediate{boolean} 是否立即执行
 * @returns debounced {Function} 返回防抖处理后的函数(带取消方法)
 */
const debounce = (fn: Function, delay: number = 300, immediate = false) => {
  let timeout: any = undefined;

  //定义防抖函数
  const debounced = (...args: any) => {
    const context = this;

    //延迟执行函数
    const later = () => {
      timeout = null;
      if (!immediate) {
        fn.apply(context, args);
      }
    };

    //判断是否立即执行
    const callNow = immediate && !timeout;

    //清除已有定时器
    timeout = setTimeout(later, delay);

    //立即执行条件判断
    if (callNow) {
      fn.apply(context, args);
    }
  };

  //添加取消方法
  debounced.cancel = () => {
    clearTimeout(timeout);
    timeout = null;
  };
  return debounced;
};

export default { debounce };
